package com.occludens.admin.datamodel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.annotation.Parent;
import com.googlecode.objectify.annotation.Subclass;

@Subclass(index=true)
public class Role extends AdminObjectDataModel {
	@Parent private Ref<Role> derived;
	@Load private List<Ref<User>> assignedUsers = new ArrayList<Ref<User>>();
	
	protected Role() {} // Mandatory for Objectify

	public Role(String name) {
		super(name);
	}
	
	public Role getDerived() {
		return this.derived.get();
	}
	
	public void setDerived (Role role) {
		this.derived = Ref.create(role);
	}
	
	public List<User> getAssignedUsers() {
		List<User> returnList = new ArrayList<User>();
		Iterator<Ref<User>> assignedUsersItr = this.assignedUsers.iterator();
		while (assignedUsersItr.hasNext()) {
			returnList.add(assignedUsersItr.next().get());
		}//End of while assignedUsersItr
		return returnList;
	}

	public void setAssignedUsers(List<User> users) {
		Iterator<User> usersItr = users.iterator();
		while (usersItr.hasNext()) {
			Ref<User> userRef = Ref.create(usersItr.next());
			if (!this.assignedUsers.contains(userRef)) {
				this.assignedUsers.add(userRef);
			}
		}//End of while attributesItr
	}

	public void addAssignedUsers(User... users) {
		for (int i=0; i<users.length; i++) {
			Ref<User> userRef = Ref.create(users[i]);
			if (!this.assignedUsers.contains(userRef)) {
				this.assignedUsers.add(userRef);
			}
		}
	}

	public void removeAssignedUsers(User... users) {
		for (int i=0; i<users.length; i++) {
			Ref<User> userRef = Ref.create(users[i]);
			if (this.assignedUsers.contains(userRef)) {
				this.assignedUsers.remove(userRef);
			}
		}
	}

}
